import json
from shlex import join

from django.core import serializers
from django.shortcuts import render, HttpResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.middleware.csrf import get_token
import hashlib
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from app01 import models
from django.utils.decorators import method_decorator
from tools.logging_dec import logging_check, logging_check_user


# Create your views here.

class AdminViews(View):
    @method_decorator(logging_check)
    def get(self, request, username=None):
        if username:
            try:
                user = models.AdminProfile.objects.get(username=username)
            except Exception as e:
                result = {'code': 410, 'error': "该用户不存在"}
                return JsonResponse(result)
            result = {'code': 200, 'data': {
                'username': user.username,
                'nickname': user.nickname,
                'password': user.password,
                'email': user.email,
                'phone': user.phone,
                'avatar': str(user.avatar),
                'sign': user.sign,
            }}

            return JsonResponse(result)

        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = models.AdminProfile.objects.all()
        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = json.loads(serializers.serialize("json", data_list))
        return JsonResponse(result)

    def post(self, request):
        json_data = request.body
        data = json.loads(json_data)
        username = data['username']
        email = data['email']
        password = data['password']
        password2 = data['password']
        phone = data['phone']
        if password != password2:
            result = {'code': 400, 'error': "两次密码不一致!"}
            return JsonResponse(result)
        old_user = models.AdminProfile.objects.filter(username=username).first()
        if old_user:
            result = {'code': 400, 'error': "用户已存在!"}
            return JsonResponse(result)
        p_m = hashlib.md5()
        p_m.update(password.encode())
        models.AdminProfile.objects.create(username=username, nickname=username, password=p_m.hexdigest(), email=email,
                                           phone=phone)
        result = {'code': 200, "username": username, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def put(self, request, username):
        json_data = request.body
        data = json.loads(json_data)
        username2 = data['username']
        oldname = data['oldusername']
        email = data['email']
        phone = data['phone']
        avatar = data['avatar']
        if oldname == 'admin':
            result = {'code': 400, "username": username, 'error': "最高权限管理员,不可修改,请联系网站管理员修改!"}
            return JsonResponse(result)
        if username != username2 and request.myuser.username != 'admin':
            result = {'code': 400, "username": username, 'error': "您没有权限,请联系最高管理员!"}
            return JsonResponse(result)
        if username2 != oldname:
            old_user = models.AdminProfile.objects.filter(username=username2).first()
            if old_user:
                result = {'code': 400, 'error': "用户已存在!"}
                return JsonResponse(result)
        models.AdminProfile.objects.filter(username=oldname).update(username=username2, nickname=username,
                                                                    email=email,
                                                                    avatar=avatar,
                                                                    phone=phone)
        result = {'code': 200, "username": username, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, username):
        json_data = request.body
        data = json.loads(json_data)
        username2 = data['username']
        if username == 'admin':
            result = {'code': 400, "username": username, 'error': "最高权限管理员,不可删除!"}
            return JsonResponse(result)
        if username2 != 'admin':
            result = {'code': 400, "username": username, 'error': "您没有权限,请联系最高管理员!"}
            return JsonResponse(result)
        models.AdminProfile.objects.filter(username=username).delete()
        result = {'code': 200, "username": username, 'data': {}}
        return JsonResponse(result)


@logging_check
def avatar(request, username):
    if request.method != "POST":
        result = {'code': 400, 'error': "请求方法错误!"}
        return JsonResponse(result)

    avatar = request.FILES['file']
    file = open("media/" + avatar.name, mode='wb')
    for chunk in avatar.chunks():
        file.write(chunk)
    file.close()
    result = {'code': 200, 'data': "http://127.0.0.1:8000/media/" + avatar.name}
    return JsonResponse(result)


class UserViews(View):
    @method_decorator(logging_check)
    def get(self, request, username=None):
        # print(username)
        if username:
            try:
                user = models.UserProfile.objects.get(username=username)
            except Exception as e:
                result = {'code': 410, 'error': "该用户不存在"}
                return JsonResponse(result)
            result = {'code': 200, 'data': {
                'username': user.username,
                'nickname': user.nickname,
                'password': user.password,
                'email': user.email,
                'phone': user.phone,
                'avatar': str(user.avatar),
                'sign': user.sign,
            }}

            return JsonResponse(result)

        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = models.UserProfile.objects.all()
        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = json.loads(serializers.serialize("json", data_list))
        return JsonResponse(result)

    def post(self, request):
        json_data = request.body
        data = json.loads(json_data)
        username = data['username']
        email = data['email']
        sex = data['sex']
        age = data['age']
        avatar = data['avatar']
        sign = data['sign']
        info = data['info']
        password = data['password']
        password2 = data['password']
        phone = data['phone']
        if password != password2:
            result = {'code': 400, 'error': "两次密码不一致!"}
            return JsonResponse(result)
        old_user = models.UserProfile.objects.filter(username=username).first()
        if old_user:
            result = {'code': 400, 'error': "用户已存在!"}
            return JsonResponse(result)
        p_m = hashlib.md5()
        p_m.update(password.encode())
        models.UserProfile.objects.create(username=username, nickname=username, password=p_m.hexdigest(), email=email,
                                          sex=sex, age=age, avatar=avatar, sign=sign, info=info,
                                          phone=phone)
        result = {'code': 200, "username": username, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def put(self, request, username):
        json_data = request.body
        data = json.loads(json_data)
        username2 = data['username']
        email = data['email']
        phone = data['phone']
        avatar = data['avatar']
        if username != username2:
            old_user = models.UserProfile.objects.filter(username=username2).first()
            if old_user:
                result = {'code': 400, 'error': "用户已存在!"}
                return JsonResponse(result)
        models.UserProfile.objects.filter(username=username).update(username=username2, nickname=username,
                                                                    email=email,
                                                                    avatar=avatar,
                                                                    phone=phone)
        result = {'code': 200, "username": username, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, username):
        json_data = request.body
        data = json.loads(json_data)
        username2 = data['username']

        if username2 != 'admin':
            result = {'code': 400, "username": username, 'error': "您没有权限,请联系最高管理员!"}
            return JsonResponse(result)
        models.UserProfile.objects.filter(username=username).delete()
        result = {'code': 200, "username": username, 'data': {}}
        return JsonResponse(result)


class ComClassView(View):
    @method_decorator(logging_check)
    def get(self, request, nid=None):
        if nid:
            try:
                dclass = models.ComClass.objects.get(c_id=nid)
            except Exception as e:
                result = {'code': 410, 'error': "该分类不存在"}
                return JsonResponse(result)
            result = {'code': 200, 'data': {
                'c_id': dclass.c_id,
                'c_name': dclass.c_name,
                'c_info': dclass.c_info,
                'c_parent_id': dclass.c_parent_id,
                'level': dclass.level,
            }}
            return JsonResponse(result)

        data_list = models.ComClass.objects.all()
        result = {'code': 200, 'data': {}}
        result['data'] = json.loads(serializers.serialize("json", data_list))
        return JsonResponse(result)

    @method_decorator(logging_check)
    def post(self, request):
        json_data = request.body
        data = json.loads(json_data)
        c_name = data['c_name']
        c_info = data['c_info']
        c_parent_id = data['c_parent_id']
        level = data['level']

        models.ComClass.objects.create(c_name=c_name, c_info=c_info, c_parent_id=c_parent_id, level=level)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def put(self, request, nid):
        json_data = request.body
        data = json.loads(json_data)
        c_name = data['c_name']
        c_info = data['c_info']
        c_parent_id = data['c_parent_id']
        level = data['level']
        models.ComClass.objects.filter(c_id=nid).update(c_name=c_name, c_info=c_info, c_parent_id=c_parent_id,
                                                        level=level)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, nid):
        models.ComClass.objects.filter(c_id=nid).delete()
        models.Goods.objects.filter(c_id=nid).update(c_id=0)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)


# @logging_check
def ParentId(request, nid):
    if nid == 0:
        parent_id_data = models.ComClass.objects.filter(level=3).values('c_id', 'c_name')
        result = {'code': 200, 'data': list(parent_id_data)}
        return JsonResponse(result)
    if nid == 10:
        parent_id_data = models.ComClass.objects.filter(level=1).values('c_id', 'c_name')
        result = {'code': 200, 'data': list(parent_id_data)}
        return JsonResponse(result)
    parent_id_data = models.ComClass.objects.exclude(level=3).exclude(level=nid).values('c_id', 'c_name', 'level')
    result = {'code': 200, 'data': list(parent_id_data)}
    # print(serializers.serialize("json", parent_id_data))
    # result['data'] = json.loads()
    return JsonResponse(result)


class GoodsViews(View):
    # @method_decorator(logging_check)
    def get(self, request, nid=None):
        if nid:
            try:
                good = models.Goods.objects.get(g_id=nid)
            except Exception as e:
                result = {'code': 410, 'error': "该商品不存在"}
                return JsonResponse(result)
            result = {'code': 200, 'data': {
                'g_name': good.g_name,
                'g_id': good.g_id,
                'g_count': good.g_count,
                'c_id': good.c_id,
                'g_info': good.g_info,
                'g_price': good.g_price,
                'g_img': str(good.g_img),
                'g_time': good.g_time,
                'g_sales': good.g_sales,
            }}

            return JsonResponse(result)

        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        data_list_raw = models.Goods.objects.raw(
            'SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id;')
        for item in data_list_raw:
            # print(json.loads(item.__dict__['g_img']))
            # print(list(item.__dict__['g_img']))
            data = {}
            data['c_name'] = item.__dict__['c_name']
            data['g_id'] = item.__dict__['g_id']
            data['c_id'] = item.__dict__['c_id']
            data['g_name'] = item.__dict__['g_name']
            data['g_time'] = item.__dict__['g_time']
            data['g_img'] = item.__dict__['g_img']
            data['g_price'] = item.__dict__['g_price']
            data['g_info'] = item.__dict__['g_info']
            data['g_count'] = item.__dict__['g_count']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)

    @method_decorator(logging_check)
    def post(self, request):
        json_data = request.body
        data = json.loads(json_data)
        g_name = data['g_name']
        c_id = data['c_id']
        g_info = data['g_info']
        g_price = data['g_price']

        g_img = data['g_img']

        g_count = data['g_count']
        old_name = models.Goods.objects.filter(g_name=g_name).first()
        if old_name:
            result = {'code': 400, 'error': "商品已存在!"}
            return JsonResponse(result)
        models.Goods.objects.create(g_name=g_name, c_id=c_id, g_info=g_info, g_price=g_price,
                                    g_img=json.dumps(g_img, ensure_ascii=False), g_count=g_count)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def put(self, request, nid=None):
        json_data = request.body
        data = json.loads(json_data)
        g_name = data['g_name']
        c_id = data['c_id']
        g_info = data['g_info']
        g_price = data['g_price']
        g_img = data['g_img']
        g_count = data['g_count']
        old_data = models.Goods.objects.filter(g_id=nid).first()
        if old_data.g_name != g_name:
            old_name = models.Goods.objects.filter(g_name=g_name).first()
            if old_name:
                result = {'code': 400, 'error': "商品已存在!"}
                return JsonResponse(result)
        models.Goods.objects.filter(g_id=nid).update(g_name=g_name, c_id=c_id, g_info=g_info, g_price=g_price,
                                                     g_img=json.dumps(g_img, ensure_ascii=False), g_count=g_count)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, nid=None):
        models.Goods.objects.filter(g_id=nid).delete()
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)


def ss_goods(request, nname=None):
    if nname and nname != "null":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        sql = "SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id WHERE g.g_name LIKE '%%" + nname + "%%' or c.c_name LIKE '%%" + nname + "%%';"
        # print(sql)
        data_list_raw = models.Goods.objects.raw(sql)
        for item in data_list_raw:
            # print(json.loads(item.__dict__['g_img']))
            # print(list(item.__dict__['g_img']))
            data = {}
            data['c_name'] = item.__dict__['c_name']
            data['g_id'] = item.__dict__['g_id']
            data['c_id'] = item.__dict__['c_id']
            data['g_name'] = item.__dict__['g_name']
            data['g_time'] = item.__dict__['g_time']
            data['g_img'] = item.__dict__['g_img']
            data['g_price'] = item.__dict__['g_price']
            data['g_info'] = item.__dict__['g_info']
            data['g_count'] = item.__dict__['g_count']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)
    page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
    page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
    data_list = []
    data_list_raw = models.Goods.objects.raw(
        'SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id;')
    for item in data_list_raw:
        # print(json.loads(item.__dict__['g_img']))
        # print(list(item.__dict__['g_img']))
        data = {}
        data['c_name'] = item.__dict__['c_name']
        data['g_id'] = item.__dict__['g_id']
        data['c_id'] = item.__dict__['c_id']
        data['g_name'] = item.__dict__['g_name']
        data['g_time'] = item.__dict__['g_time']
        data['g_img'] = item.__dict__['g_img']
        data['g_price'] = item.__dict__['g_price']
        data['g_info'] = item.__dict__['g_info']
        data['g_count'] = item.__dict__['g_count']
        data_list.append(data)

    paginator = Paginator(data_list, page_size)
    count = paginator.count
    result = {'code': 200, 'data': {}, "count": count}
    try:
        data_list = paginator.page(page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    result['data'] = list(data_list)
    return JsonResponse(result)


def fl_goods(request, nname=None):
    if nname and nname != "null":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        sql = "SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id WHERE c.c_name LIKE '%%" + nname + "%%';"
        # print(sql)
        data_list_raw = models.Goods.objects.raw(sql)
        for item in data_list_raw:
            # print(json.loads(item.__dict__['g_img']))
            # print(list(item.__dict__['g_img']))
            data = {}
            data['c_name'] = item.__dict__['c_name']
            data['g_id'] = item.__dict__['g_id']
            data['c_id'] = item.__dict__['c_id']
            data['g_name'] = item.__dict__['g_name']
            data['g_time'] = item.__dict__['g_time']
            data['g_img'] = item.__dict__['g_img']
            data['g_price'] = item.__dict__['g_price']
            data['g_info'] = item.__dict__['g_info']
            data['g_count'] = item.__dict__['g_count']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)
    page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
    page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
    data_list = []
    data_list_raw = models.Goods.objects.raw(
        'SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id;')
    for item in data_list_raw:
        # print(json.loads(item.__dict__['g_img']))
        # print(list(item.__dict__['g_img']))
        data = {}
        data['c_name'] = item.__dict__['c_name']
        data['g_id'] = item.__dict__['g_id']
        data['c_id'] = item.__dict__['c_id']
        data['g_name'] = item.__dict__['g_name']
        data['g_time'] = item.__dict__['g_time']
        data['g_img'] = item.__dict__['g_img']
        data['g_price'] = item.__dict__['g_price']
        data['g_info'] = item.__dict__['g_info']
        data['g_count'] = item.__dict__['g_count']
        data_list.append(data)

    paginator = Paginator(data_list, page_size)
    count = paginator.count
    result = {'code': 200, 'data': {}, "count": count}
    try:
        data_list = paginator.page(page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    result['data'] = list(data_list)
    return JsonResponse(result)


class BannerView(View):
    # @method_decorator(logging_check)
    def get(self, request, nid=None):
        # print(nid)
        if nid:
            try:
                banner = models.Banner.objects.get(banner_id=nid)
            except Exception as e:
                result = {'code': 410, 'error': "该商品不存在"}
                return JsonResponse(result)
            result = {'code': 200, 'data': {
                'banner_name': banner.banner_name,
                'banner_img': str(banner.banner_img),
            }}

            return JsonResponse(result)

        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = models.Banner.objects.all().order_by("banner_name")
        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = json.loads(serializers.serialize("json", data_list))
        return JsonResponse(result)

    @method_decorator(logging_check)
    def post(self, request):
        json_data = request.body
        data = json.loads(json_data)
        banner_name = data['banner_name']
        banner_img = data['banner_img']
        models.Banner.objects.create(banner_name=banner_name, banner_img=banner_img)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def put(self, request, nid=None):
        json_data = request.body
        data = json.loads(json_data)
        banner_name = data['banner_name']
        banner_img = data['banner_img']
        models.Banner.objects.filter(banner_id=nid).update(banner_name=banner_name, banner_img=banner_img)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, nid=None):
        models.Banner.objects.filter(banner_id=nid).delete()
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)


@logging_check
def sell(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        data_list_raw = models.Sell_num_statistics.objects.raw(
            'SELECT  s.sn_id,s.jh_number,s.xs_number,c.c_name FROM sell_num_statistics as s JOIN dsmall.com_class as c ON s.c_id = c.c_id ORDER BY s.xs_number/s.jh_number Asc ;')
        for item in data_list_raw:
            data = {}
            data['sn_id'] = item.__dict__['sn_id']
            data['c_name'] = item.__dict__['c_name']
            data['xs_number'] = item.__dict__['xs_number']
            data['jh_number'] = item.__dict__['jh_number']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


@logging_check
def dos(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        data_list_raw = models.Dos_statistics.objects.raw(
            'SELECT  d.dos_id,d.cp_grade,d.hp_grade,d.zp_grade,g.g_name FROM dos_statistics as d JOIN dsmall.goods as g ON d.g_id = g.g_id;')
        for item in data_list_raw:
            data = {}
            data['cp_grade'] = item.__dict__['cp_grade']
            data['hp_grade'] = item.__dict__['hp_grade']
            data['zp_grade'] = item.__dict__['zp_grade']
            data['g_name'] = item.__dict__['g_name']
            data_list.append(data)
        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


@logging_check
def per(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list_all = models.Performance_statistics.objects.all()
        data_list = []
        for item in data_list_all:
            data = {}
            data['c_name'] = item.c_name
            data['percentage'] = item.percentage
            data['kpi'] = item.kpi
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


@logging_check
def oldsell(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list_all = models.Old_Sell_statistics.objects.all().order_by('year_number')
        data_list = []
        for item in data_list_all:
            data = {}
            data['year_kpi'] = item.year_kpi
            data['year_number'] = item.year_number
            data['qt_number'] = item.qt_number
            data['dn_number'] = item.dn_number
            data['sj_number'] = item.sj_number
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


@logging_check
def age(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list_all = models.Age_statistics.objects.all()
        data_list = []
        for item in data_list_all:
            data = {}
            data['people_number'] = item.people_number
            data['man_number'] = item.man_number
            data['woman_number'] = item.woman_number
            data['year_number'] = item.year_number
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


@logging_check
def ret(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list_all = models.Return_statistics.objects.all()
        data_list = []
        for item in data_list_all:
            data = {}
            data['th_number'] = item.th_number
            data['ret_number'] = item.ret_number
            data['year_number'] = item.year_number
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


@logging_check
def qian(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = 4  # 防止url直接传过来字符串的页码
        data_list = []
        data_list_raw = models.Sell_num_statistics.objects.raw(
            'SELECT  s.sn_id,s.jh_number,s.xs_number,c.c_name FROM sell_num_statistics as s JOIN dsmall.com_class as c ON s.c_id = c.c_id ORDER BY s.xs_number DESC ;')
        for item in data_list_raw:
            data = {}
            data['sn_id'] = item.__dict__['sn_id']
            data['c_name'] = item.__dict__['c_name']
            data['xs_number'] = item.__dict__['xs_number']
            data['jh_number'] = item.__dict__['jh_number']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


# @logging_check
def mark(request):
    if request.method == "GET":
        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list_all = models.Market_research_statistics.objects.all()
        data_list = []
        for item in data_list_all:
            data = {}
            data['sc_number'] = item.sc_number
            data['yes_number'] = item.yes_number
            data['no_number'] = item.no_number
            data['vyes_number'] = item.vyes_number
            data['vno_number'] = item.vno_number
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)


class ShoppingCart(View):
    # @method_decorator(logging_check)
    def get(self, request, user=None):
        # print(user)
        if user:
            data_list = []
            sql = "SELECT * FROM shopping_cart s JOIN goods g ON s.good_id = g.g_id WHERE user_name = \"" + user +"\";"
            # print(sql)
            data_list_raw = models.Goods.objects.raw(sql)
            for item in data_list_raw:
                # print(json.loads(item.__dict__['g_img']))
                # print(list(item.__dict__['g_img']))
                data = {}
                data['g_id'] = item.__dict__['g_id']
                data['g_name'] = item.__dict__['g_name']
                data['g_info'] = item.__dict__['g_info']
                data['g_price'] = item.__dict__['g_price']
                data['g_img'] = item.__dict__['g_img']
                data['shopping_cart_num'] = item.__dict__['shopping_cart_num']
                data['shopping_cart_id'] = item.__dict__['shopping_cart_id']
                data_list.append(data)

            result = {'code': 200, 'data': {}}
            result['data'] = list(data_list)
            return JsonResponse(result)

        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        data_list_raw = models.Goods.objects.raw(
            'SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id;')
        for item in data_list_raw:
            # print(json.loads(item.__dict__['g_img']))
            # print(list(item.__dict__['g_img']))
            data = {}
            data['c_name'] = item.__dict__['c_name']
            data['g_id'] = item.__dict__['g_id']
            data['c_id'] = item.__dict__['c_id']
            data['g_name'] = item.__dict__['g_name']
            data['g_time'] = item.__dict__['g_time']
            data['g_img'] = item.__dict__['g_img']
            data['g_price'] = item.__dict__['g_price']
            data['g_info'] = item.__dict__['g_info']
            data['g_count'] = item.__dict__['g_count']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)

    @method_decorator(logging_check_user)
    def post(self, request, user=None):
        json_data = request.body
        data = json.loads(json_data)
        shopping_cart_num = data['shopping_cart_num']
        good_id = data['good_id']
        try:
            res = models.Shopping_cart.objects.filter(user_name=user, good_id=good_id)
            print(res[0].shopping_cart_num)
            res2 = models.Shopping_cart.objects.filter(user_name=user, good_id=good_id).update(shopping_cart_num=res[0].shopping_cart_num+1)
            result = {'code': 200, 'data': {'esg':"修改成功"}}
            return JsonResponse(result)
        except Exception as e:
            res = models.Shopping_cart.objects.create(user_name=user, good_id=good_id, shopping_cart_num=shopping_cart_num)
            result = {'code': 200, 'data': {'esg':"添加成功"}}
            return JsonResponse(result)

    @method_decorator(logging_check_user)
    def put(self, request, user=None):
        # print(user)
        json_data = request.body
        data = json.loads(json_data)
        shopping_cart_num = data['shopping_cart_num']
        models.Shopping_cart.objects.filter(shopping_cart_id=user).update(shopping_cart_num=shopping_cart_num)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, user=None):
        models.Shopping_cart.objects.filter(shopping_cart_id=user).delete()
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

class UserAddress(View):
    @method_decorator(logging_check)
    def get(self, request, user=None,nid=None):
        if user:
            if nid:
                try:
                    user = models.UserAddress.objects.get(id=nid)
                except Exception as e:
                    result = {'code': 410, 'error': "该用户不存在"}
                    return JsonResponse(result)
                result = {'code': 200, 'data': {
                    'username': user.username,
                    'name': user.name,
                    'state': user.state,
                    'phone': user.phone,
                    'city': user.city,
                    'detail':user.detail,

                }}
                return JsonResponse(result)
            try:
                user = models.UserAddress.objects.filter(username=user)
            except Exception as e:
                result = {'code': 410, 'error': "该用户不存在"}
                return JsonResponse(result)
            result = {'code': 200, 'data': list(user.values())}
            return JsonResponse(result)


        page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
        page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
        data_list = []
        data_list_raw = models.Goods.objects.raw(
            'SELECT  g.*,c.c_name FROM goods as g left JOIN dsmall.com_class as c ON g.c_id = c.c_id;')
        for item in data_list_raw:
            # print(json.loads(item.__dict__['g_img']))
            # print(list(item.__dict__['g_img']))
            data = {}
            data['c_name'] = item.__dict__['c_name']
            data['g_id'] = item.__dict__['g_id']
            data['c_id'] = item.__dict__['c_id']
            data['g_name'] = item.__dict__['g_name']
            data['g_time'] = item.__dict__['g_time']
            data['g_img'] = item.__dict__['g_img']
            data['g_price'] = item.__dict__['g_price']
            data['g_info'] = item.__dict__['g_info']
            data['g_count'] = item.__dict__['g_count']
            data_list.append(data)

        paginator = Paginator(data_list, page_size)
        count = paginator.count
        result = {'code': 200, 'data': {}, "count": count}
        try:
            data_list = paginator.page(page)
        except PageNotAnInteger:
            data_list = paginator.page(1)
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
        result['data'] = list(data_list)
        return JsonResponse(result)

    @method_decorator(logging_check)
    def post(self, request, user=None,nid=None):
        json_data = request.body
        data = json.loads(json_data)
        username = data['username']
        name = data['name']
        phone = data['phone']
        city = data['city']
        detail = data['detail']
        state = data['state']
        if state == 1:
            models.UserAddress.objects.filter(username=user).update(state=2)
        models.UserAddress.objects.create(username=username, name=name, phone=phone, city=city,
                                                         detail=detail, state=state)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def put(self, request, user=None,nid=None):
        json_data = request.body
        data = json.loads(json_data)
        username = data['username']
        name = data['name']
        phone = data['phone']
        city = data['city']
        detail = data['detail']
        state = data['state']
        if state == 1:
            models.UserAddress.objects.filter(username=user).update(state=2)
        models.UserAddress.objects.filter(id=nid).update(username=username, name=name, phone=phone, city=city,
                                                     detail=detail, state=state)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, user=None, nid=None):
        models.UserAddress.objects.filter(id=nid).delete()
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)


class Product_Order(View):
    # @method_decorator(logging_check)
    def get(self, request, user=None):
        if user:
            state = request.GET.get("state")
            data_list = []
            if state == '5':
                sql = "SELECT * FROM product_order p JOIN goods g ON p.good_id = g.g_id WHERE user_name = \"" + user + "\";"
            else:
                sql = "SELECT * FROM product_order p JOIN goods g ON p.good_id = g.g_id WHERE user_name = \"" + user + "\" and product_order_state = " + state + ";"
            print(sql)
            data_list_raw = models.Product_Order.objects.raw(sql)
            for item in data_list_raw:
                # print(json.loads(item.__dict__['g_img']))
                # print(list(item.__dict__['g_img']))
                data = {}
                data['g_id'] = item.__dict__['g_id']
                data['g_name'] = item.__dict__['g_name']
                data['g_info'] = item.__dict__['g_info']
                data['g_price'] = item.__dict__['g_price']
                data['g_img'] = item.__dict__['g_img']
                data['product_order_id'] = item.__dict__['product_order_id']
                data['product_order_money'] = item.__dict__['product_order_money']
                data['product_order_num'] = item.__dict__['product_order_num']
                data['product_order_state'] = item.__dict__['product_order_state']
                data_list.append(data)

            result = {'code': 200, 'data': {}}
            result['data'] = list(data_list)
            return JsonResponse(result)
        else:
            id = request.GET.get("id")
            if id:
                sql = "SELECT * FROM product_order p JOIN goods g ON p.good_id = g.g_id  WHERE product_order_id = " + id + ";"
                data_list_raw = models.Product_Order.objects.raw(sql)
                data_list = []
                for item in data_list_raw:
                    data = {}
                    data['g_id'] = item.__dict__['g_id']
                    data['g_name'] = item.__dict__['g_name']
                    data['g_info'] = item.__dict__['g_info']
                    data['username'] = item.__dict__['user_name']
                    data['g_price'] = item.__dict__['g_price']
                    data['g_img'] = item.__dict__['g_img']
                    data['product_order_id'] = item.__dict__['product_order_id']
                    data['product_order_money'] = item.__dict__['product_order_money']
                    data['product_order_num'] = item.__dict__['product_order_num']
                    data['product_order_state'] = item.__dict__['product_order_state']
                    data_list = data
                    result = {'code': 200, 'data': {}}
                    result['data'] = data_list
                    return JsonResponse(result)

            else:
                state = request.GET.get("state")
                page = int(request.GET.get("currentPage"))  # 防止url直接传过来字符串的页码
                page_size = int(request.GET.get("pagesize"))  # 防止url直接传过来字符串的页码
                data_list = []
                if state:
                    sql = "SELECT * FROM product_order p JOIN goods g ON p.good_id = g.g_id  WHERE product_order_state = " + state + ";"
                else:
                    sql = "SELECT * FROM product_order p JOIN goods g ON p.good_id = g.g_id;"

                data_list_raw = models.Product_Order.objects.raw(sql)
                for item in data_list_raw:
                    data = {}
                    data['g_id'] = item.__dict__['g_id']
                    data['g_name'] = item.__dict__['g_name']
                    data['g_info'] = item.__dict__['g_info']
                    data['username'] = item.__dict__['user_name']
                    data['g_price'] = item.__dict__['g_price']
                    data['g_img'] = item.__dict__['g_img']
                    data['product_order_id'] = item.__dict__['product_order_id']
                    data['product_order_money'] = item.__dict__['product_order_money']
                    data['product_order_num'] = item.__dict__['product_order_num']
                    data['product_order_state'] = item.__dict__['product_order_state']
                    data_list.append(data)
                paginator = Paginator(data_list, page_size)
                count = paginator.count
                result = {'code': 200, 'data': {}, "count": count}
                try:
                    data_list = paginator.page(page)
                except PageNotAnInteger:
                    data_list = paginator.page(1)
                except EmptyPage:
                    data_list = paginator.page(paginator.num_pages)
                result['data'] = list(data_list)
                return JsonResponse(result)


    @method_decorator(logging_check_user)
    def post(self, request, user=None):
        json_data = request.body
        data = json.loads(json_data)
        product_order_money = data['product_order_money']
        good_id = data['g_id']
        product_order_num = data['product_order_num']
        product_order_state = data['product_order_state']

        res = models.Product_Order.objects.create(good_id=good_id, product_order_money=product_order_money,
                                                  user_name=user,
                                                  product_order_num=product_order_num,
                                                  product_order_state=product_order_state)
        print(res)
        result = {'code': 200, 'data': {'esg': "添加成功"}}
        return JsonResponse(result)


    @method_decorator(logging_check_user)
    def put(self, request, user=None):
        # print(user)
        json_data = request.body
        data = json.loads(json_data)
        product_order_id = data['product_order_id']
        product_order_state = data['product_order_state']
        if product_order_state == 0:
            models.Product_Order.objects.filter(product_order_id=product_order_id).update(product_order_state=0)
        if product_order_state == 2:
            models.Product_Order.objects.filter(product_order_id=product_order_id).update(product_order_state=2)
        if product_order_state == 3:
            models.Product_Order.objects.filter(product_order_id=product_order_id).update(product_order_state=3)
        if product_order_state == 4:
            models.Product_Order.objects.filter(product_order_id=product_order_id).update(product_order_state=4)
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)

    @method_decorator(logging_check)
    def delete(self, request, user=None):
        models.Shopping_cart.objects.filter(shopping_cart_id=user).delete()
        result = {'code': 200, 'data': {}}
        return JsonResponse(result)
        product_order

@logging_check
def Product_Order_List(request,user=None):
    if request.method == "POST":
        json_data = request.body
        data = json.loads(json_data)
        for item in data:
            print(item)
            shopping_cart_id = item['shopping_cart_id']
            product_order_money = item['product_order_money']
            good_id = item['good_id']
            product_order_num = item['product_order_num']
            product_order_state = item['product_order_state']
            res = models.Product_Order.objects.create(good_id=good_id, product_order_money=product_order_money,
                                                      user_name=user,
                                                      product_order_num=product_order_num,
                                                      product_order_state=product_order_state)
            res = models.Shopping_cart.objects.filter(shopping_cart_id = shopping_cart_id).delete()
            print(res)
        result = {'code': 200, 'data': {'esg': "下单成功"}}
        return JsonResponse(result)
